package com.contatos.control;

import com.contatos.model.Contato;

import javax.swing.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Christian
 * Date: 01/05/14
 * Time: 16:30
 * To change this template use File | Settings | File Templates.
 */
public class ContatoControl {

    public ContatoControl(){

    }

    public int writeContato(Contato c){
        DataAccessObject dataAccessObject = new DataAccessObject();
        String nome = c.getNome();
        String endereco = c.getEndereco();
        String email = c.getEmail();
        String telefone = c.getTelefones();

        //Monta a StringSQL
        String sql = "INSERT INTO contatos VALUES ('"+nome+"','"+endereco+"','"+email+"','"+telefone+"')";
        int result = dataAccessObject.executeUpdate(sql);
        dataAccessObject.closeConnection();
        return result;
    }

    public ArrayList<Contato> readContato(String nome){
        ArrayList<Contato> contatos = new ArrayList<Contato>();
        DataAccessObject dataAccessObject = new DataAccessObject();
        String sql = "SELECT * FROM contatos WHERE nome = '"+ nome +"' ORDER BY nome";
        if(nome == null){
            sql = "SELECT * FROM contatos ORDER BY nome";
        }
        ResultSet resultSet = dataAccessObject.executeQuery(sql);
        try {
            resultSet.first();
            while(!resultSet.isAfterLast()){
                contatos.add(new Contato(resultSet.getString(1),resultSet.getString(3),resultSet.getString(2),resultSet.getString(4)));
                resultSet.next();
            }
        } catch (SQLException e){
            System.err.println(e.getMessage());
        } finally {
            dataAccessObject.closeConnection();
        }

        return contatos;
    }

    public int updateContato(Contato c, String chave){
        DataAccessObject dataAccessObject = new DataAccessObject();
        String nome = c.getNome();
        String endereco = c.getEndereco();
        String email = c.getEmail();
        String telefone = c.getTelefones();

        //Monta a StringSQL
        String sql = "UPDATE contatos SET nome='"+nome+"',endereco='"+endereco+"',email='"+email+"',telefone='"+telefone+"' WHERE nome='"+chave+"'";
        int result = dataAccessObject.executeUpdate(sql);
        dataAccessObject.closeConnection();
        return result;
    }

    public int deleteContato(String chave){
        DataAccessObject dataAccessObject = new DataAccessObject();

        //Monta a StringSQL
        String sql = "DELETE FROM contatos WHERE  nome='"+chave+"'";
        int result = dataAccessObject.executeUpdate(sql);
        dataAccessObject.closeConnection();
        return result;
    }
}
